package com.coolwen.controller;

import com.alibaba.fastjson.JSON;
import com.coolwen.entity.Category;
import com.coolwen.service.CategoryService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Created by user on 2016/6/29.
 */
@Controller
@RequestMapping("/admin/category/")
public class CategoryController {

    private Logger logger = Logger.getLogger(getClass());


    @Autowired
    private CategoryService ctyService;

    @RequestMapping("/list")
    public String list(Model model, String name) {

        model.addAttribute("cs", ctyService.list(name));
        return "category/list";
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute("category", new Category());
        return "category/add";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String add(Category category, BindingResult br) {
        if (br.hasErrors()) {
            //如果有错误直接跳转到add视图

            return "category/add";
        }
        ctyService.add(category);
        logger.info("address添加:" + JSON.toJSON(category));
        return "redirect:/admin/category/list";
    }

    @RequestMapping("show/{id}")
    public String show(@PathVariable int id, Model model) {
//        addService.delete(id);
        Category category = ctyService.load(id);
        model.addAttribute("category", category);
        return "category/show";
    }


    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String update(@PathVariable int id, Model model) {
        Category category = ctyService.load(id);
        model.addAttribute("category", category);
        return "category/update";
    }

    @RequestMapping(value = "update/{id}", method = RequestMethod.POST)
    public String update(@PathVariable int id, Category category, BindingResult br, Model model) {
        if (br.hasErrors()) {
            //category.getId();
            return "category/update";
        }
        category.setId(id);
        ctyService.update(category);
        logger.info("address更新:" + JSON.toJSON(category));
//        addService.update(address);
        return "redirect:/admin/category/list";
    }

    @RequestMapping("delete/{id}")
    public String delete(@PathVariable int id) {
        ctyService.delete(id);
        return "redirect:/admin/category/list";
    }


}
